package pearson.automation.forms;

import java.util.ArrayList;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;

import pearson.automation.assets.AssetList;
import pearson.automation.assets.Note;
import pearson.automation.forms.SearchResultsForm.AssetCategory;

import framework.BaseForm;
import framework.elements.Button;
import framework.elements.ElementList;
import framework.elements.Label;
import framework.elements.Link;
import framework.elements.TextBox;

public class RightHandPanel extends BaseForm {

    public enum RightHandPanelTab { SUGGESTED, LIBRARY, NOTES };
    
    private static Label rightHandPanel =
        new Label(By.xpath("//aside"), "Righthand Panel");
    private static RightHandPanelTab currentTab = RightHandPanelTab.SUGGESTED;
    
    private Link suggestedTab =
        new Link(By.linkText("Suggested"), "Suggested tab");
    private Link libraryTab   =
        new Link(By.linkText("Library"),   "Library tab");
    private Link notesTab     =
        new Link(By.linkText("Notes"),     "Notes tab");
    
    private TextBox suggestedSearchBox =
        new TextBox(By.name("keyword"), "Search box");
    private TextBox othersSearchBox    =
        new TextBox(By.name("tag"), "Search box");
    private Button  searchBoxFilter    =
        new Button(By.className("ajax-search-module-filter-button"),
                "Search box filter button");
    private ElementList categoriesBox  =
        new ElementList(By.xpath(
                "//ul[contains(@class, 'ajax-search-module-filter-list')]//li"),
                "Categories");
    private Label searchBoxFilterOpened =
        new Label(By.className("ajax-search-module-search"),
                "Searchbox Filter toggle element");
    
    private ElementList results = new ElementList(By.xpath(
            "//ul[contains(@class, 'ajax-search-module-results')]"
          + "//li[contains(@class,'contain')]"), "Elements");
    public AssetList assets = new AssetList(
            "//ul[contains(@class, 'ajax-search-module-results')]",
            "//li[contains(@class,'contain')]");
    private Label emptySearchResults = new Label(By.xpath(
            "//ul[contains(@class, 'ajax-search-module-results')]"),
            "Empty search label");
    private Label resultsCount =
        new Label(By.className("infinite-scroll-loader"), "Results");
    private Label loader =
        new Label(By.className("loader"), "Loader");
    
    public RightHandPanel() {
        super(rightHandPanel.getLocator(), "Right hand panel");
    }

    public void openTab(RightHandPanelTab tab) {
        switch(tab) {
            case SUGGESTED:
                suggestedTab.clickAndWait(); break;
            case LIBRARY:
                libraryTab.clickAndWait(); break;
            case NOTES:
                notesTab.clickAndWait(); break;
        }
        currentTab = tab;
    }

    public String getSearchBoxText() {
        if (currentTab == RightHandPanelTab.SUGGESTED) {
            return suggestedSearchBox.getElement().getAttribute("value");
        } else {
            return othersSearchBox.getElement().getAttribute("value");
        }
    }
    
    public String getSearchBoxPlaceholder() {
        if (currentTab == RightHandPanelTab.SUGGESTED) {
            return "";
        } else {
            return othersSearchBox.getElement().getAttribute("placeholder");
        }
    }
    
    public int getResultsCount() {
        return results.getListElements().size();
    }

    public ArrayList<String[]> getAssets() {
        ArrayList<String[]> result = new ArrayList<String[]>();
        for (WebElement item: results.getListElements()) {
            String[] elementParams = new String[2];
            if (currentTab != RightHandPanelTab.NOTES) {
                elementParams[0] = item.getText();
                elementParams[1] = item.getAttribute("data-content-type");
                result.add(elementParams);
            }
        }
        return result;
    }
    
    public Note getNoteByIndex(int index) {
        return new Note(String.format("(//ul[contains(@class,'notes-list')]/li)[%d]", index));
    }

    public int getMoreElements() {
        // Scroll to the bottom of the page
        ((JavascriptExecutor) browser.getDriver()).executeScript(
                "li_array =" +
                " document.body.getElementById('edit-sidebar')" +
                ".getElementsByTagName('li');" +
                "li_array[li_array.length-1].scrollIntoView()");
        
        // Get new count of viewed assets
        return getResultsCount();
    }
    
    public int getMoreElementsOnDetailsTab() {
        // Scroll to the bottom of the page
        ((JavascriptExecutor) browser.getDriver()).executeScript(
                "li_array =" +
                " document.body.getElementById('contextual-nav')" +
                ".getElementsByTagName('li');" +
                "li_array[li_array.length-1].scrollIntoView()");
        
        // Get new count of viewed assets
        return getResultsCount();
    }

    public void search(String string) {
        if (currentTab == RightHandPanelTab.SUGGESTED) {
            suggestedSearchBox.setText(string);
            suggestedSearchBox.submit();
        } else {
            othersSearchBox.setText(string);
            othersSearchBox.submit();
        }
        loader.waitForElementDissapear();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
     }

    public boolean hasEmptyResultsLabel() {
        //results.waitForElementDissapear();
        return emptySearchResults.isPresent();
    }

    public boolean isDisplayed() {
        rightHandPanel.assertIsPresent();
        return rightHandPanel.getElement().getCssValue("right").equals("0px");
    }

    public void openCategoriesSelectorInSearchBox() {
        if (!searchBoxFilterOpened.getElement()
                .getAttribute("class").contains("opened")) {
            searchBoxFilter.clickAndWait();
        }
        categoriesBox.waitAndAssertIsPresent();
    }

    public void selectSearchCategory(AssetCategory asset) {
        categoriesBox.selectListElement(asset.toString());
        resultsCount.isPresent();
    }
    
    public AssetDetailsPopupForm clickOnResult(int index) {
        results.selectListElement(index);
        return new AssetDetailsPopupForm();
    }
    
}
